package com.uaf.aes.contoller;

import com.uaf.aes.bean.ResponData;
import com.uaf.aes.utils.AESUtilsDemo;
import com.uaf.aes.utils.FileStreamUtils;
import com.uaf.aes.utils.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.URLDecoder;

/**
 * @author cailu
 * @filename indexController
 * @description
 * @date 2020/4/29 17:42
 */
@Controller
public class IndexController {

	private static String PATH = "D:\\uaren\\aeskey\\aes.txt";

	@GetMapping("/index")
	public String index() {
		return "index";
	}

	@GetMapping("/token")
	@ResponseBody
	public ResponData token() throws IOException {
		//生成秘钥
		String codeKey = RandomUtils.randomHexString(16);
		//保存秘钥
		FileStreamUtils.writeToString(PATH, codeKey);
		//生成token
		String token = RandomUtils.randomUUID();
		//生成url
		String url = "http://localhost:8680/index?token=" + token;
		ResponData responData = new ResponData();
		responData.setToken(token);
		responData.setCodeKey(codeKey);
		responData.setUrl(url);
		return responData;
	}

	@PostMapping("save")
	@ResponseBody
	public String save(@RequestBody String data) throws Exception {
		data = URLDecoder.decode(data, "utf-8");
		System.out.println("加密:" + data);
		//String codeKey = reids.get("codeKey"); //redis中取codeKey
		String codeKey = FileStreamUtils.readToString(PATH);
		String str = AESUtilsDemo.decrypt(data, codeKey);
		System.out.println("解密:" + str);
		return "000000";
	}

	@PostMapping("encrypt")
	@ResponseBody
	public String encryptWeb(@RequestBody String token) throws Exception {
		String codeKey = FileStreamUtils.readToString(PATH);
		System.out.println("token:" + token);
		String data = "{\n" +
				"\t\"name\": \"测试\",\n" +
				"\t\"age\": \"18\",\n" +
				"\t\"ads\": \"我是中文\",\n" +
				"\t\"adasd\": \"我是\"\n" +
				"}";
		String str = AESUtilsDemo.encrypt(data, codeKey);
		System.out.println("加密:" + str);
		return str;
	}


}
